from django.shortcuts import render
from django.http import JsonResponse
from django.db.models import Count
from web import models
import collections


def statistics(request, project_id):
    return render(request, 'personal_management/statistics.html')


def statistics_priority(request, project_id):
    """按优先级分组"""
    # 找到所有的问题，根据优先级分组，每个优先级的问题数量
    # 得到开始时间和结束时间
    start = request.GET.get('start')
    end = request.GET.get('end')
    # 构建一个有序列表向前端传去
    data_dict = collections.OrderedDict()
    for key, text in models.Issues.priority_choices:
        # 把这个优先级写入列表
        data_dict[key] = {'name': text, 'y': 0}
    # 去查询所有的分组得到的数量
    result = models.Issues.objects.filter(project_id=project_id, creator_datetime__gte=start,
                                          creator_datetime__lt=end).values('priority').annotate(ct=Count('id'))
    # 把分组得到的数据更新到data_dict中
    for item in result:
        data_dict[item['priority']]['y'] = item['ct']
    return JsonResponse({"status": True, "data": list(data_dict.values())})


def project_user(request, project_id):
    start = request.GET.get('start')
    end = request.GET.get('end')
    # 1、所有项目以及未指派
    all_user_dict = collections.OrderedDict()
    all_user_dict[request.tracer.project.creator.id] = {
        # 创建者的项目状态
        'name': request.tracer.project.creator.username,
        'status': {item[0]: 0 for item in models.Issues.status_choices}
    }
    all_user_dict[None] = {
        'name': '未指派',
        'status': {item[0]: 0 for item in models.Issues.status_choices}
    }

    # 所有成员的项目
    user_list = models.ProjectUser.objects.filter(project_id=project_id)
    for item in user_list:
        all_user_dict[item.user_id] = {
            'name': item.user.username,
            'status': {item[0]: 0 for item in models.Issues.status_choices}
        }
    # 去数据库获相关问题
    issues = models.Issues.objects.filter(project_id=project_id, creator_datetime__gte=start,
                                          creator_datetime__lt=end)
    for item in issues:
        # 成员是否指派
        if not item.assign:
            all_user_dict[None]['status'][item.status] += 1
        else:
            all_user_dict[item.assign_id]['status'][item.status] += 1
    categories = [data['name'] for data in all_user_dict.values()]
    data_result_dict = collections.OrderedDict()
    for item in models.Issues.status_choices:
        data_result_dict[item[0]] = {'name': item[1], 'data': []}
    for key, text in models.Issues.status_choices:
        for row in all_user_dict.values():
            count = row['status'][key]
            data_result_dict[key]['data'].append(count)
    context = {
        'status': True,
        'data': {
            'categories': categories,
            'series': list(data_result_dict.values())
        }
    }
    return JsonResponse(context)
